import { Form, Input, message, Modal, Select, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { updateUser } from '../api';

const MyModal: React.FC<
{
  isUpdate: any;
  isOpen: any;
  setIsUpdate: any;
  setIsModalOpen: any;
  modalData: any;
}> = ({setIsUpdate,setIsModalOpen,isOpen,isUpdate,modalData}) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const onCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    if (modalData) {    
      console.log(modalData);
    form.setFieldsValue({
      username: modalData?.username || '',
      account: modalData?.account || '',
      permissions: (modalData?.permissions === 0? '管理员': '用户')|| '',
    });
  }
  },[modalData,isOpen]);

 //表单提交
 const onFinish = async () => {
  setLoading(true);    
    const data = {
      id: modalData.id,
      username: form.getFieldValue('username'),
      account: form.getFieldValue('account'),
      permissions: form.getFieldValue('permissions') === '管理员' ? 0 : form.getFieldValue('permissions') === '用户'? 1: form.getFieldValue('permissions'),
      createdTime: modalData.createdTime
    }
    const res = await updateUser(data);
    if (res.code === 200) {
      setIsUpdate(!isUpdate);
      form.resetFields();
      setIsModalOpen(false);
    } else {
      message.error(res.message);
    }

  setLoading(false);
 }

 return (<div>
  <Modal
        title={"修改弹窗"}
        open={isOpen}
        onOk={onFinish}
        onCancel={onCancel}
        afterClose={() => form.resetFields()}
      >
        <Spin spinning={loading}>
          <Form
            name="修改"
            form={form}
            // className={styles.form}
            style={{ overflow: 'auto', maxHeight: '500px' }}
          >
            <Form.Item
              label="用户名"
              colon={false}
              // className={styles.formSelect}
              name={'username'}
            >
              <Input placeholder="请输入" />
              </Form.Item>
              <Form.Item
              label="账号"
              colon={false}
              // className={styles.formSelect}
              name={'account'}
            >
              <Input placeholder="请输入" />
              </Form.Item>
              <Form.Item
              label="身份"
              colon={false}
              // className={styles.formSelect}
              name={'permissions'}
            >
              <Select>
                <Select.Option key={0} value={0}>
                  管理员
                </Select.Option>
                <Select.Option key={1} value={1}>
                  普通用户
                </Select.Option>
              </Select>
              </Form.Item>
          </Form>
          </Spin>
          </Modal>
 </div>);}

export default MyModal;
